package cn.yj.netty.support.test;

import cn.yj.netty.common.CommandCode;
import cn.yj.netty.common.Const;
import cn.yj.netty.support.test.protocol.BasePacket;
import cn.yj.netty.support.test.protocol.Header;

import java.lang.reflect.Field;
import java.util.UUID;

/**
 * 传输对象
 *
 * @author 永健
 * @since 2022-02-15 12:20
 */
public class MessageProtocol extends BasePacket<String> {
    public String toProtocolStr() {
        Header header = getHeader();
        StringBuffer buffer = new StringBuffer();
        buffer.append(Const.DELIMITER_START).append("\n");
        Field[] declaredFields = header.getClass().getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            Field declaredField = declaredFields[i];
            declaredField.setAccessible(true);
            String name = declaredField.getName();
            try {
                Object value = declaredField.get(header);
                buffer.append(name).append(":").append(value != null? value.toString() : "").append("\n");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        buffer.append("\n");
        buffer.append("body:" + getBody());
        buffer.append("\n");
        buffer.append(Const.DELIMITER_END);
        return buffer.toString();
    }

    public static MessageProtocol newMessageProtocolHearPack(){
        Header header = new Header();
        header.setTimestamp(System.currentTimeMillis());
        header.setSessionId(UUID.randomUUID().toString());
        header.setCommandCode(CommandCode.HEART_BEAT.getCode());
        header.setHost("127.0.0.1");
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setHeader(header).setBody(Const.EMPTY);
        return messageProtocol;
    }
}
